from rest_framework import serializers
from jewelry.models import Banner
from jewelry.models import Product


class BannerSerializer(serializers.ModelSerializer):
    product_id = serializers.PrimaryKeyRelatedField(
        queryset=Product.objects.all(),
        source='product',
        required=False,
        allow_null=True
    )

    class Meta:
        model = Banner
        fields = [
            'id', 'title', 'image', 'link', 'order',
            'is_active', 'start_time', 'product_id'
        ]
        read_only_fields = ['image']

    def validate_title(self, value):
        """标题验证"""
        if len(value) < 2:
            raise serializers.ValidationError("标题至少需要2个字符")
        return value

    def validate_order(self, value):
        """优先级验证"""
        if value < 0:
            raise serializers.ValidationError("优先级不能为负数")
        return value

    def validate(self, data):
        """综合验证"""
        # 检查是否关联了有效商品
        product = data.get('product')
        if product and not Product.objects.filter(id=product.id).exists():
            raise serializers.ValidationError("关联商品不存在")
        return data
